import Vuex from 'vuex';
import config from '/static/script/config';
import {
	getBalances,
	getCoinUsdt
} from '../http/api.js';

const store = new Vuex.Store({
	state: {
		address: uni.getStorageSync('wallerAddress') || "",
		chainId: uni.getStorageSync('chainId') || "",
		allchains: uni.getStorageSync('allchains') || [],
		rpc: uni.getStorageSync('rpc') || "",
		addressInfo: null,
		choinInfo: null,
		chainInfo: null,
		broswer: uni.getStorageSync('broswer') || [],
		Appstatus:1
	},
	mutations: {
		setAppstatus(state,Appstatus){
			state.Appstatus = Appstatus;
		},
		setAddress(state, address) {
			uni.setStorageSync('wallerAddress', address);
			state.address = address;
		},
		setChainId(state, chainId) {
			uni.setStorageSync('chainId', String(chainId));
			state.chainId = String(chainId);
		},
		setAllchains(state, allchains) {
			uni.setStorageSync('allchains', allchains);
			state.allchains = allchains;
		},
		setBroswer(state, broswer) {
			uni.setStorageSync('broswer', broswer);
			state.broswer = broswer;
		},
		setRpc(state, rpc) {
			uni.setStorageSync('rpc', rpc);
			state.rpc = rpc;
			let rpclist = uni.getStorageSync('rpclist') || [];
			let newRpclist = rpclist.map(chain => {
				if (chain.chainId == state.chainId) {
					return {
						...chain,
						defultRPC: rpc
					};
				}
				return chain;
			})
			if (newRpclist.length > 0) {
				uni.setStorageSync('rpclist', newRpclist);
			}
		},
		SET_ADDRESS_INFO(state, info) {
			state.addressInfo = info;
		},
		SET_CHOINS_INFO(state, info) {
			state.choinInfo = info;
		},
		SET_CHAIN_INFO(state, info) {
			state.chainInfo = info;
		},
	},
	actions: {
		async fetchInfo({
			commit
		}, {
			address,
			chainId
		}) {
			try {
				uni.showLoading({
					title: '加载中',
					mask: true
				});

				const addressRes = await selectAddress(address, chainId);
				const choinRes = await selectChoin(address, chainId);
				const chainInfo = getChainInfo(chainId);
				commit('SET_CHAIN_INFO', chainInfo || null);
				commit('SET_ADDRESS_INFO', addressRes[0] || null);
				commit('SET_CHOINS_INFO', choinRes || []);
				const tokens = choinRes.map(item => item.tokenaddress);
				if (tokens.length > 0) {
					const param = {
						chaintype: chainInfo.chainType,
						chainid: chainInfo.chainId,
						address: address,
						tokens: tokens.join(','),
					};
					await updateTokenPrices(commit, param, choinRes, address, chainId);
					await updateTokenBalances(commit, param, choinRes, address, chainId);
				}
				

			} catch (error) {
				// console.error("Error fetching data:", error);
			} finally {
				setTimeout(() => uni.hideLoading(), 1500);
			}
		},
		updateName({
			state
		}, newName) {
			return updateField('name', state.address, state.chainId, newName);
		},
		updatePass({
			state
		}, newPassword) {
			return updateField('password', state.address, state.chainId, newPassword);
		},
		updatePassTilp({
			state
		}, newPasswordTilp) {
			return updateField('passwordTilp', state.address, state.chainId, newPasswordTilp);
		},
		delWallet({
			commit
		}, {
			address,
			chainId
		}) {
			return new Promise(async (resolve, reject) => {
				try {
					const addressRes = await deleteAddress(address, chainId);
					const choinRes = await deleteChoin(address, chainId);
					resolve({
						addressRes,
						choinRes
					});
				} catch (error) {
					console.error("Error deleting wallet:", error);
					reject(error);
				}
			});
		},
	},
	getters: {
		getAddress: state => state.address,
		getChainId: state => state.chainId,
		getAllchains: state => state.allchains,
		getRpc: state => state.rpc,
		addressInfo: state => state.addressInfo,
		choinInfo: state => state.choinInfo,
		chainInfo: state => state.chainInfo,
		broswer: state => state.broswer,
		Appstatus: state => state.Appstatus,
		tokensymbol(state) {
			const info = state.chainInfo?.coin.find(item => item.contract == config.defaultAddress);
			return info?.symbol;
		},
	}
});

// 辅助函数
async function selectAddress(address, chainId) {
	return uni.$db.select('list', {
		from: 'addressList',
		where: [{
			address: `= "${address}"`,
			chainId: `= "${chainId}"`
		}]
	});
}

async function selectChoin(address, chainId) {
	return uni.$db.select('list', {
		from: 'choinList',
		where: [{
			address: `= "${address}"`,
			chainId: `= "${chainId}"`
		}]
	});
}

function getChainInfo(chainId) {
	return uni.getStorageSync('allchains').find(item => item.chainId == chainId);
}

async function updateTokenPrices(commit, param, choinRes, address, chainId) {
	const res = await getCoinUsdt(param);
	if (res.code == 200) {
		const updatePromises = res.data.map(item => {
			return uni.$db.update('list', {
				from: 'choinList',
				set: {
					tokenprice: item.price
				},
				where: [{
					chainId: `= "${chainId}"`,
					address: `= "${address}"`,
					tokenaddress: `= "${item.token}"`
				}]
			});
		});
		await Promise.all(updatePromises);
		const updatedChoinRes = await selectChoin(address, chainId);
		commit('SET_CHOINS_INFO', updatedChoinRes || []);
	}
}

async function updateTokenBalances(commit, param, choinRes, address, chainId) {
	const res = await getBalances(param);
	if (res.code == 200) {
		const updatePromises = res.data.map(item => {
			return uni.$db.update('list', {
				from: 'choinList',
				set: {
					tokennum: item.balance,
					tokenimg: item.ico
				},
				where: [{
					chainId: `= "${chainId}"`,
					address: `= "${address}"`,
					tokenaddress: `= "${item.contract}"`
				}]
			});
		});
		await Promise.all(updatePromises);
		const updatedChoinRes = await selectChoin(address, chainId);
		commit('SET_CHOINS_INFO', updatedChoinRes || []);
	}
}

async function updateField(field, address, chainId, value) {
	return uni.$db.update('list', {
		from: 'addressList',
		set: {
			[field]: value
		},
		where: [{
			address: `= "${address}"`,
			chainId: `= "${chainId}"`
		}]
	});
}

async function deleteAddress(address, chainId) {
	return uni.$db.delete('list', {
		from: 'addressList',
		where: [{
			address: `= "${address}"`,
			chainId: `= "${chainId}"`
		}]
	});
}

async function deleteChoin(address, chainId) {
	return uni.$db.delete('list', {
		from: 'choinList',
		where: [{
			address: `= "${address}"`,
			chainId: `= "${chainId}"`
		}]
	});
}

export default store;